package  com.lepu.app.fun.tool.ymsjb.remind;

import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.View;

import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;

/**
 * 闹钟唤醒程序主进程
 */
@SuppressWarnings("deprecation")
@SuppressLint("Wakelock")
public class RemindSoundActivity extends BaseFragmentActivity{

    public MediaPlayer player;
    public Alarm alarm;

    private AudioManager mAudioManager = null;
    private int mCurrentStreamVolume = 0;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.remind_sound_activity);

        mAudioManager = (AudioManager) this
                .getSystemService(Context.AUDIO_SERVICE);
        mCurrentStreamVolume = mAudioManager
                .getStreamVolume(AudioManager.STREAM_RING);

        player = new MediaPlayer();

        alarm = (Alarm) getIntent().getSerializableExtra("remindAlarm");

        if (alarm == null)
        {
            return;
        }

        // 获取电源管理器对象
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        // 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
        PowerManager.WakeLock wl = pm.newWakeLock(
                PowerManager.ACQUIRE_CAUSES_WAKEUP
                        | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
        // 点亮屏幕
        wl.acquire();
        // 得到键盘锁管理器对象
        KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        // 参数是LogCat里用的Tag
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
        // 解锁
        kl.disableKeyguard();

        // 播放铃声
        try {
            Uri alert = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_ALARM);
            player.setDataSource(this, alert);
            @SuppressWarnings("unused")
			final AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

            //设置最大声音的一半
            int maxVolume = mAudioManager
                    .getStreamMaxVolume(AudioManager.STREAM_RING);
            mAudioManager.setStreamVolume(AudioManager.STREAM_RING, maxVolume/2,
                    0);

            player.setAudioStreamType(AudioManager.STREAM_RING);
            player.setLooping(false);
            player.prepare();
            player.start();

            int playDuration = player.getDuration();

            if(playDuration > 0)
            {
                mHandler.sendEmptyMessageDelayed(100,playDuration);
            }
            // 播放完毕监听,三星手机收不到回调
//            player.setOnCompletionListener(new OnCompletionListener() {
//
//                @Override
//                public void onCompletion(MediaPlayer mp) {
//
//                    //恢复最初音量
//                    mAudioManager.setStreamVolume(AudioManager.STREAM_RING,
//                            mCurrentStreamVolume, 0);
//                }
//            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        String title = "";
        String message = "";

        // 显示dialog
        title = "疫苗提醒";

        StringBuilder sb = new StringBuilder();
        sb.append(String.format("时间：%s",alarm.showTime));
        sb.append("\n");
        sb.append(String.format("备注：%s",alarm.note));
        
        message = sb.toString();
        showDialog(title, message);

        // 重新启用自动加锁
        kl.reenableKeyguard();
        wl.release();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void showDialog(String title, String message) {
        MyDialog dialog = new MyDialog(this)
                .setTitle(title).setMessage(message)
                .setPositiveButton(R.string.app_ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        stop();
                        finish();

                        //程序还没有启动，跳转程序
//                        if(MainActivity.getInstance() == null){
//                            Intent intent = new Intent();
//                            intent.setClass(RemindSoundActivity.this, WelcomeOneActivity.class);
//                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            startActivity(intent);
//                        }
                    }
                })
                .setNegativeButton(R.string.cancel, new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        stop();
                        finish();
                    }
                });

        dialog.create(null);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.showMyDialog();
    }

    @SuppressLint("HandlerLeak")
	Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if(msg.what == 100){
                stop();
            }
        }
    };

    //停止播放
    public void stop() {
        if (player != null) {

            mAudioManager.setStreamVolume(AudioManager.STREAM_RING,
                    mCurrentStreamVolume, 0);

            player.stop();
            player.reset();
            player.release();
            player = null;
        }
    }


}
